package com.yyaccp.itrip.auth.service;

import com.yyaccp.itrip.auth.exception.UserLoginFailedException;
import com.yyaccp.itrip.beans.domain.ItripUser;
import com.yyaccp.itrip.beans.vo.TokenVo;
import com.yyaccp.itrip.dao.ItripUserMapper;
import com.yyaccp.itrip.utils.MD5;
import com.yyaccp.itrip.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 天天向上 （john.yi@qq.com）
 * @date 2020/11/16.
 */
@Service
public class LoginService {
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private ItripUserMapper userMapper;

    public ItripUser login(String name, String password) throws UserLoginFailedException {
        ItripUser user =  userMapper.selectByUserCode(name);
        if(user == null) {
            throw new UserLoginFailedException("用户不存在");
        }
        if(user.getActivated().equals(0)) {
            throw new UserLoginFailedException("账号未激活");
        }
        if(!user.getUserPassword().equals(MD5.md5(password))) {
            throw new UserLoginFailedException("密码错误");
        }
        return user;
    }

    public TokenVo createToken(ItripUser user, String userAgent) {
        return tokenUtil.createToken(user, userAgent);
    }
}
